package com.wanglei.service.impl;

import com.wanglei.domain.ResponseResult;
import com.wanglei.domain.entity.LoginUser;
import com.wanglei.domain.entity.User;
import com.wanglei.domain.vo.BlogUserLoginVo;
import com.wanglei.domain.vo.UserInfoVo;
import com.wanglei.enums.AppHttpCodeEnum;
import com.wanglei.service.BlogLoginService;
import com.wanglei.utils.BeanCopyUtils;
import com.wanglei.utils.JwtUtil;
import com.wanglei.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class BlogLoginServiceImpl implements BlogLoginService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        //AuthenticationManager authenticate进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果没通过 给出对应的提示
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或者密码错误");
        }
        //如果用户通过了 使用userid生成一个jwt //这里也key写在登陆成功的处理器里！！
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String id = loginUser.getUser().getId().toString();//Long 转 String
        String jwt = JwtUtil.createJWT(id);
        //把完整的用户信息存入redis userid作为key
        redisCache.setCacheObject("bloglogin:"+id,loginUser);

        //把token 和 用户部分信息(vo) 响应给前端
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        BlogUserLoginVo vo = new BlogUserLoginVo(jwt,userInfoVo);
        return ResponseResult.okResult(vo);
    }

    @Override
    public ResponseResult logout() {
        //获取存在SecurityContextHolder中的loginUser
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //获取userid
        Long id = loginUser.getUser().getId();
        //删除redis中的值
        redisCache.deleteObject("bloglogin:"+id);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
